<template>
    <!-- 顶部拖拽区域 -->
    <!-- 标签栏 -->
    <div class="window-container">
        <div class="tab-bar-container" @mousedown="handleMouseDown" @dblclick="maximizeWindow">
            <div id="tab-bar" class="tab-bar">
                <div id="new-tab" class="new-tab-button">
                    <el-icon class="icon">
                        <Plus />
                    </el-icon>
                </div>
                <!-- 标签页将在这里动态添加 -->
            </div>
            <!-- 窗口控制按钮（必须设置为不可拖拽） -->
            <div class="window-controls" style="-webkit-app-region: no-drag;">
                <el-icon class="control-icon" @click="minimizeWindow">
                    <Minus />
                </el-icon>
                <el-icon class="control-icon" @click="maximizeWindow">
                    <FullScreen />
                </el-icon>
                <el-icon class="control-icon close" @click="closeWindow">
                    <Close />
                </el-icon>
            </div>
        </div>
        <!-- 工具栏 -->
        <div class="toolbar">
            <el-icon class="toolbar-icon" @click="goBack" style="-webkit-app-region: no-drag;">
                <Back />
            </el-icon>
            <el-icon class="toolbar-icon" @click="goForward" style="-webkit-app-region: no-drag;">
                <Right />
            </el-icon>
            <el-icon class="toolbar-icon" @click="refresh" style="-webkit-app-region: no-drag;">
                <RefreshRight />
            </el-icon>
            <el-input :prefix-icon="Search" class="urlpath" id="urlpath" v-model="tabpath" @keyup.enter="handleUrlEnter"
                style="-webkit-app-region: no-drag;"></el-input>
            <el-icon class="toolbar-icon">
                <User />
            </el-icon>
            <el-icon class="toolbar-icon" title="邮件" @click="handleMail" style="-webkit-app-region: no-drag;">
                <Setting />
            </el-icon>
        </div>
    </div>
    <!-- 使用封装的右键菜单组件 -->
    <!-- <ContextMenu ref="contextMenuRef" :menu-items="contextMenuItems" @select="onMenuItemSelect"
            @hide="onMenuHide" /> -->


</template>
<script setup>
import { Plus, Search, Back, Right, RefreshRight, Minus, FullScreen, Close, Setting, User, IceCream } from '@element-plus/icons-vue'
import { onMounted, onUnmounted, ref } from "vue";
import { ipcApiRoute } from "@/api";
import { ipc } from "@/utils/ipcRenderer";
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const tabpath = ref('');
const isDragging = ref(false);
const initMousePos = ref({ x: 0, y: 0 });
const activateTabEl = ref(null);
const handleMouseDown = (event) => {
    // 检查是否应该允许拖拽
    if (shouldAllowDrag(event.target) && event.button === 0) {//event.button === 0左键点击
        initMousePos.value = { x: event.clientX, y: event.clientY };
        isDragging.value = true;
        ipc.send('win-drag-start', { x: event.clientX, y: event.clientY });
        // 阻止默认行为和事件冒泡
        event.preventDefault();
        event.stopPropagation();
        document.body.style.transition = 'none'; // 关闭过渡动画
    }
};

const shouldAllowDrag = (element) => {
    // 检查元素是否属于不可拖拽的区域
    const noDragElements = element.closest(
        '.no-drag, .tab, .control-icon, .toolbar-icon, input, button, a, .close, .new-tab-button'
    );
    // 如果点击在这些元素上，则不允许拖拽
    return !noDragElements;
};

const handleMail = () => {
    let url = "http://fdmail.fdauto.com:8003/webmail/index.do?osName=windows";
    ipc.send("create-tab", url);
}
const handleUrlEnter = () => {
    // 通知主进程加载输入的 URL 或刷新当前页面
    let url = tabpath.value.trim();
    // 如果URL不为空且不包含协议头，则自动添加http://
    if (url && !/^https?:\/\//i.test(url)) {
        url = 'http://' + url;
        tabpath.value = url;
    }
    ipc.send('load-url', url);
};
const minimizeWindow = () => {
    ipc.send('minimize-window');
};
const maximizeWindow = () => {
    ipc.send('maximize-window');
};
const closeWindow = () => {
    ipc.send('close-window');
};
const goBack = () => {
    // 后退
    ipc.send('go-back');
};
const goForward = () => {
    // 前进
    ipc.send('go-forward');
};
const refresh = () => {
    // 刷新当前页面
    ipc.send('refresh-tab');
};

// 添加键盘事件处理
const handleKeyDown = (event) => {
    // 检查是否按下了 Ctrl+Tab 或 Ctrl+Shift+Tab
    if (event.ctrlKey && event.key === 'Tab') {
        event.preventDefault();
        if (event.shiftKey) {
            // Ctrl+Shift+Tab - 切换到上一个标签页
            ipc.send('switch-to-next-tab');
        } else {
            // Ctrl+Tab - 切换到下一个标签页
            ipc.send('switch-to-prev-tab');
        }
    }
    if (event.key == "F5") {
        refresh();
    }
};

// 添加标签页元素
function addTabElement(tab) {
    const newTabButton = document.getElementById('new-tab');
    const tabBar = document.getElementById('tab-bar');
    const tabElement = document.createElement('div');
    tabElement.className = 'tab';
    tabElement.style.webkitAppRegion = 'no-drag';
    tabElement.dataset.id = tab.id;
    if (tab.isActive) {
        tabElement.classList.add('active');
    }
    // 检查是否处于加载状态
    if (tab.loading) {
        tabElement.classList.add('loading');
    }
    // 提取 favicon 路径
    let faviconUrl = '';
    try {
        const urlObj = new URL(tab.url);
        faviconUrl = `${urlObj.origin}/favicon.ico`;
    } catch (e) {
        // 如果 URL 无效，则不显示 favicon
        faviconUrl = '';
    }

    let closeEl = tab.hideclose ? '' : '<span class="close">×</span> ';
    tabElement.innerHTML = `
    ${faviconUrl ? `<img src="${faviconUrl}" class="favicon" onerror="this.style.display='none'">` : '<span class="favicon-placeholder"></span>'}
            <span class="title">${tab.title}</span>
            ${closeEl}
        `;
    // 点击标签页激活
    tabElement.addEventListener('click', (e) => {
        if (!e.target.classList.contains('close')) {
            ipc.send('activate-tab', tab.id)
            e.stopPropagation();
        }
    });

    tabElement.addEventListener('contextmenu', (e) => {
        // 阻止默认右键菜单
        e.preventDefault();
        e.stopPropagation();
        ipc.send('show-tab-context-menu', tab.id);
    });
    // 点击关闭按钮
    const closeBtn = tabElement.querySelector('.close');
    closeBtn && closeBtn.addEventListener('click', (e) => {
        ipc.send('close-tab', tab.id)
        e.stopPropagation();
    });
    if (activateTabEl.value) {
        tabBar.insertBefore(tabElement, activateTabEl.value.nextSibling);
    } else {
        tabBar.insertBefore(tabElement, newTabButton);
    }
}

// 更新标签页元素
function updateTabElement(tab) {
    const tabElement = document.querySelector(`.tab[data-id="${tab.id}"]`);
    if (tabElement) {
        tabElement.querySelector('.title').textContent = tab.title;
        // 更新 favicon
        let faviconUrl = '';
        try {
            const urlObj = new URL(tab.url);
            faviconUrl = `${urlObj.origin}/favicon.ico`;
        } catch (e) {
            faviconUrl = '';
        }

        let faviconEl = tabElement.querySelector('.favicon');
        if (faviconUrl) {
            if (!faviconEl) {
                faviconEl = document.createElement('img');
                faviconEl.className = 'favicon';
                faviconEl.onerror = function () { this.style.display = 'none'; };
                tabElement.insertBefore(faviconEl, tabElement.querySelector('.title'));
            }
            faviconEl.src = faviconUrl;
            faviconEl.style.display = '';
        } else if (faviconEl) {
            faviconEl.remove();
        }
    }
    if (activateTabEl.value == tabElement) {
        tabpath.value = tab.url;
    }
}

// 激活标签页元素
function activateTabElement(tabObj) {
    let tabId = tabObj.id;
    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.remove('active');
    });
    const tabElement = document.querySelector(`.tab[data-id="${tabId}"]`);
    if (tabElement) {
        tabpath.value = tabObj.url;
        tabElement.querySelector('.title').textContent = tabObj.title;
        tabElement.classList.add('active');
        activateTabEl.value = tabElement;
    }
}

// 移除标签页元素
function removeTabElement(tabId) {
    const tabElement = document.querySelector(`.tab[data-id="${tabId}"]`);
    if (tabElement) {
        tabElement.remove();
    }
}
function tabCreatedHandler(event, tab) {
    addTabElement(tab);
}
function tabUpdatedHandler(event, tab) {
    updateTabElement(tab);
}
function tabActivatedHandler(event, tab) {
    activateTabElement(tab);
}
function tabClosedHandler(event, tabId) {
    removeTabElement(tabId);
}

// 添加标签页加载开始处理
function tabLoadingStart(event, tabData) {
    const tabElement = document.querySelector(`.tab[data-id="${tabData.id}"]`);
    if (tabElement) {
        // 添加加载中样式
        tabElement.classList.add('loading');
        tabElement.querySelector('.title').textContent = tabData.title;
    }
}

// 添加标签页加载结束处理
function tabLoadingStop(event, tabData) {
    const tabElement = document.querySelector(`.tab[data-id="${tabData.id}"]`);
    if (tabElement) {
        // 移除加载中样式
        tabElement.classList.remove('loading');
        tabElement.querySelector('.title').textContent = tabData.title;
    }
}

const handleNewTabClick = () => {
    let lastTab = document.getElementById("tab-bar").children[document.getElementById("tab-bar").children.length - 2];
    let tabId = lastTab.dataset.id;
    ipc.send('activate-tab', tabId);
    ipc.send("create-tab");
};


onMounted(
    async () => {
        let dragOffset = { x: 0, y: 0 };
        let logurl = await ipc.invoke(ipcApiRoute.getLoginUrl, "loginUrl");
        let url = route.params.url || logurl
        // tabpath.value = url
        ipc.send(ipcApiRoute.openHome, { url });
        const newTabButton = document.getElementById('new-tab');
        // 创建新标签页
        newTabButton.removeEventListener('click', handleNewTabClick);
        newTabButton.addEventListener('click', handleNewTabClick);

        // 从主进程接收标签页事件
        ipc.on('tab-created', tabCreatedHandler);
        ipc.on('tab-updated', tabUpdatedHandler);
        ipc.on('tab-activated', tabActivatedHandler);
        ipc.on('tab-closed', tabClosedHandler);

        // 添加加载状态事件监听
        ipc.on('tab-loading-start', tabLoadingStart);
        ipc.on('tab-loading-stop', tabLoadingStop);

        ipc.invoke(ipcApiRoute.getTabs).then((tabs) => {
            tabs.forEach(tab => addTabElement(tab));
        });
        ipc.on('set-default', (event) => { router.push({ path: "/login" }); })
        window.addEventListener('keydown', handleKeyDown);
        document.addEventListener('mousemove', (e) => {
            if (!isDragging.value) {
                return;
            }
            dragOffset.x += e.movementX; // 使用 movementX 更精确
            dragOffset.y += e.movementY;
            ipc.send('win-dragging', dragOffset.x, dragOffset.y);
        });
        document.addEventListener('mouseup', () => {
            if (!isDragging.value) {
                return;
            }
            isDragging.value = false;
            // 鼠标释放：将视觉位移应用到原生窗口
            ipc.send('win-drag-end', dragOffset.x, dragOffset.y);
            dragOffset = { x: 0, y: 0 };
        });
    })

onUnmounted(() => {
    ipc.removeListener('tab-created', tabCreatedHandler);
    ipc.removeListener('tab-updated', tabUpdatedHandler);
    ipc.removeListener('tab-activated', tabActivatedHandler);
    ipc.removeListener('tab-closed', tabClosedHandler);
    ipc.removeListener('tab-loading-start', tabLoadingStart);
    ipc.removeListener('tab-loading-stop', tabLoadingStop);
    window.removeEventListener('keydown', handleKeyDown);
    // 移除事件监听器
    const newTabButton = document.getElementById('new-tab');
    if (newTabButton) {
        newTabButton.removeEventListener('click', handleNewTabClick);
    }
});
</script>
<style lang="less">
body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
    /* 确保 transform 不影响布局 */
    transform-origin: 0 0;
}

.window-container {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.tab-bar-container {
    // -webkit-app-region: drag;
    cursor: grab;
    background-color: #CECECE;
    position: relative;
    height: 40px;
    border-bottom: 0;
    display: flex;
    align-items: center;
}

/* 确保所有交互元素都不影响拖拽 */
.tab-bar-container * {
    -webkit-app-region: no-drag;
}

/* 排除特定的交互元素 */
.tab-bar-container .window-controls,
.tab-bar-container .tab,
.tab-bar-container #new-tab {
    -webkit-app-region: no-drag;
}

.tab-bar {
    -webkit-app-region: no-drag;
    /* 标签本身不可拖拽 */
    padding-top: 7px;
    display: flex;
    align-items: center;
    flex: 1;
    height: 100%;
    overflow-x: auto;
}

.new-tab-button {
    -webkit-app-region: no-drag;
    /* 新建标签按钮不可拖拽 */
    cursor: pointer;
    padding: 4px 5px;
    font-size: 14px;
    color: #666;

    .icon {
        margin: 5px;
    }
}

.new-tab-button:hover {
    background-color: #e0e0e0
}

.window-controls {
    -webkit-app-region: no-drag;
    display: flex;
    margin-top: -10px;
    height: 30px;
    align-items: center;
    background-color: #CECECE;

    .control-icon {
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        -webkit-app-region: no-drag;

        &:hover {
            background-color: #e0e0e0;
        }

        &.close:hover {
            background-color: #ff5555;
            color: white;
        }
    }
}

.toolbar {
    z-index: 10;
    display: flex;
    align-items: center;
    padding: 0 5px;
    background-color: #ffffff;
    border-bottom: 1px solid #ccc;
    flex-shrink: 0;

    .toolbar-icon {
        height: 34px;
        width: 34px;
        -webkit-app-region: no-drag;
        cursor: pointer;
    }

    .toolbar-icon:hover {
        background-color: #DCDCDC;
    }

    .el-input__wrapper {
        border-radius: 5px;
    }

    .urlpath {
        flex: 1;
        margin: 0 10px;
        -webkit-app-region: no-drag;
    }
}



.content {
    flex: 1;
    overflow: hidden;
}

.tab {
    padding: 10px;
    cursor: pointer;
    height: 100%;
    // border-color: #D3E3FD;
    // border-right: 1px solid #D3E3FD;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 200px;
    display: flex;
    align-items: center;
    transition: box-shadow 0.2s ease; // 添加过渡效果
    position: relative;

    // 使用伪元素创建右边框
    &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 5px; // 距离顶部的距离
        height: calc(100% - 10px); // 边框高度，这里设置为标签高度减去10px
        width: 1px;
        background-color: #949090;
    }

    // 加载中状态样式
    &.loading {
        &::before {
            content: '';
            margin: 5px;
            display: inline-block;
            width: 12px;
            height: 12px;
            border: 2px solid #cccccc;
            border-radius: 50%;
            border-top-color: #409eff;
            animation: spin 1s linear infinite;
        }
    }
}

.tab .favicon {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    vertical-align: middle;
    flex-shrink: 0;
}

.tab .favicon-placeholder {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 8px;
    flex-shrink: 0;
}

// 旋转动画

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}


.tab .title {
    flex: 1;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: left;
    /* 允许flex项目收缩到小于内容宽度 */
}

.tab .close {
    flex: 0 0 auto;
    /* 不伸缩，保持原始大小 */
    padding: 0 5px;
}

.tab:hover {
    background-color: #DBDBDB;
    box-shadow:
        inset 2px 0 4px -2px rgba(231, 232, 233, 0.4),
        inset -2px 0 4px -2px rgba(231, 232, 233, 0.4);

    // 隐藏右边框
    &::after {
        display: none;
    }
}

.tab.active {
    background-color: white;
    border-radius: 6px 6px 0 0;
    box-shadow:
        inset 2px 0 4px -2px rgba(231, 232, 233, 0.4),
        inset -2px 0 4px -2px rgba(231, 232, 233, 0.4);

    // 隐藏右边框
    &::after {
        display: none;
    }

    // 激活状态下的加载动画
    &.loading {
        ::before {
            border-top-color: #409eff;
        }
    }
}



.tab .close {
    color: #888;
}

.tab .close:hover {
    color: #000;
}

webview {
    width: 100%;
    height: calc(100vh - 30px);
}
</style>